package com.lms.demo.fileservice.filter;

import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StreamUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @Author: 李孟帅
 * @CreateTime: 2020-12-29 15:01
 * @Description:
 */
public class RewriteHttpServletRequest extends HttpServletRequestWrapper {
    private String encoding = "GBK";
    private byte[] requestBodyIniBytes;


    public RewriteHttpServletRequest(HttpServletRequest request) throws IOException {
        super(request);
        ServletInputStream stream = request.getInputStream();
        String requestBody = StreamUtils.copyToString(stream, Charset.forName(encoding));
        requestBodyIniBytes = requestBody.getBytes(encoding);
    }


    @Override
    public ServletInputStream getInputStream() {

        final ByteArrayInputStream in;
        in = new ByteArrayInputStream(requestBodyIniBytes);

        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {

                return in.read();
            }
        };
    }


}
